package com.tianqu.tms.www.car.action;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.validator.GenericValidator;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

import com.tianqu.tms.core.base.Logger;
import com.tianqu.tms.core.base.TmsAction;
import com.tianqu.tms.core.base.UserContext;
import com.tianqu.tms.core.util.Registry;
import com.tianqu.tms.core.util.StringUtil;
import com.tianqu.tms.core.util.TmsConstants;
import com.tianqu.tms.core.util.TmsFieldChecks;
import com.tianqu.tms.dto.MarketCarInfoDto;
import com.tianqu.tms.entity.Car;
import com.tianqu.tms.www.car.actionform.CarPrivilegedCarDetailActionForm;
import com.tianqu.tms.www.car.controller.CarPrivilegedCarDetailController;

/**
 * 特权车管理 - 信息录入(修改画面)
 * @author zhao-qc
 *
 */
public class CarPrivilegedToUpdateAction extends TmsAction {

	private Logger logger = Logger.getLogger(CarPrivilegedToUpdateAction.class);
	private static final String TOUPDATE = "toUpdate";
	@Override
	protected ActionForward doAction(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response,
			UserContext uc) throws Exception {
		logger.debug(this.getClass().getName() + "#execute was called.");
		
		CarPrivilegedCarDetailActionForm privilegedCarForm = (CarPrivilegedCarDetailActionForm) uc.getInputForm();
		MarketCarInfoDto marketCarInfoDto = (MarketCarInfoDto) uc.getAttribute(VIEWHELP);
		//车牌前两位
		String lPlate = Registry.getConfig(TmsConstants.TMS_DEFLICENSEPLATE_KEY);
		if (lPlate.equals(privilegedCarForm.getLicensePlate())){
			privilegedCarForm.setLicensePlate("");
		}
		// 非第一次加载页面
		privilegedCarForm.setFlg("1");
		
		// 未改变之前的 车牌号码 和 易碎贴编号
		String oldLicensePlate;
		String oldTempLicensePlate;
		if(StringUtil.isNullOrBlank(marketCarInfoDto.getLicensePlate())){
			oldLicensePlate = privilegedCarForm.getLicensePlate();
		}else{
			oldLicensePlate = marketCarInfoDto.getLicensePlate();
		}
		if(StringUtil.isNullOrBlank(marketCarInfoDto.getLicensePlate())){
			oldTempLicensePlate = privilegedCarForm.getTempLicensePlate();
		}else{
			oldTempLicensePlate = marketCarInfoDto.getTempLicensePlate();
		}
		
		// 到系统功能配置表（tms_configure）获取参数名为gateType的值，如果值为“3：易碎贴+车牌识别”，那么车牌号码和易碎贴编号都不录入，页面提示“【U8005】车牌号码和易碎贴编号至少录入一个。”
		String gateType = Registry.getConfig(TmsConstants.GATE_TYPE);//易碎贴+车牌识别;
		if ("3".endsWith(gateType)) {
			if(StringUtil.isNullOrBlank(privilegedCarForm.getLicensePlate()) && StringUtil.isNullOrBlank(privilegedCarForm.getTempLicensePlate())){
				setErrorsToRequest(request, TmsConstants.U8005 ,null);
				return mapping.findForward(TOUPDATE);
			}	
		}
		/*// 车牌号码 必须输入
		if(StringUtil.isNullOrBlank(privilegedCarForm.getLicensePlate())){
			String[] param = {"车牌号码"};
			setErrorsToRequest(request, TmsConstants.U0005 ,param);
			return mapping.findForward(TOUPDATE);
		}
		// 易碎贴编号 必须输入
		if(StringUtil.isNullOrBlank(privilegedCarForm.getTempLicensePlate())){
			String[] param = {"易碎贴编号"};
			setErrorsToRequest(request, TmsConstants.U0005 ,param);
			return mapping.findForward(TOUPDATE);
		}
		else{
			if(!GenericValidator.matchRegexp(privilegedCarForm.getTempLicensePlate(),"^[0-9a-zA-Z]*$")){
				String[] param = {"易碎贴编号"};
				setErrorsToRequest(request, TmsConstants.U0014, param);
				return mapping.findForward(TOUPDATE);
			}
		}*/
		// 车牌号码和易碎贴编号只能录入一个
		if(!StringUtil.isNullOrBlank(privilegedCarForm.getLicensePlate()) && !StringUtil.isNullOrBlank(privilegedCarForm.getTempLicensePlate())){			
			ActionMessages message = new ActionMessages();
		    message.add("msg",new ActionMessage("车牌号码和易碎贴编号只能录入一个。",false));
		    this.saveErrors(request,message);
			return mapping.findForward(TOUPDATE);
		}
//		if(!StringUtil.isNullOrBlank(privilegedCarForm.getTempLicensePlate())){
//			if(!GenericValidator.matchRegexp(privilegedCarForm.getTempLicensePlate(),"^[0-9a-zA-Z]*$")){
//				String[] param = {"易碎贴编号"};
//				setErrorsToRequest(request, TmsConstants.U0014, param);
//				return mapping.findForward(TOUPDATE);
//			}
//		}
		// 有效结束时间 必须输入
		if(StringUtil.isNullOrBlank(privilegedCarForm.getEndDate())){
			String[] param = {"有效结束时间"};
			setErrorsToRequest(request, TmsConstants.U0005 ,param);
			return mapping.findForward(TOUPDATE);
		}
		else{
			if(!isValidDate(privilegedCarForm.getEndDate())){
				String[] param = {"有效结束日期", "YYYYMMDD"};
				setErrorsToRequest(request, TmsConstants.U0018, param); 
				return mapping.findForward(TOUPDATE);
			}else{
				if ("1".equals(privilegedCarForm.getValidStatus())){
					SimpleDateFormat formatDate = new SimpleDateFormat("yyyy-MM-dd");
					// 当前系统日期
					String nowDateStr = formatDate.format(new Date());
					Date nowDate = formatDate.parse(nowDateStr);
					// 有效结束日期	
					Date endDate = formatDate.parse(privilegedCarForm.getEndDate());
					// 比较--有效结束日期没有比当前系统日期大：页面提示“【U0021】{0}只能填写今天以后的日期（包括今天在内）。”
					if (endDate.compareTo(nowDate) < 0) {
						String[] param = {"有效结束日期"};
						setErrorsToRequest(request, TmsConstants.U0021, param); 
						return mapping.findForward(TOUPDATE);
					}
				}
			}
		}
		// 车牌号码：页面提示“【U1002】车牌号码输入错误，正确的输入格式：第1位是省份汉字代号，第2位是英文字母，第3-7位是英文字母或数字，最后1位可以是汉字“挂，领，学””
		if(!StringUtil.isNullOrBlank(privilegedCarForm.getLicensePlate()) && !TmsFieldChecks.isCarLicense(privilegedCarForm.getLicensePlate()) ){
        	setErrorsToRequest(request, TmsConstants.U1002 ,null);
			return  mapping.findForward(TOUPDATE);
	    }
		
		Car car = Car.getInstance();
		if(!privilegedCarForm.getLicensePlate().equals(oldLicensePlate)){
			String licensePlate = "";
			licensePlate = car.findInputInfoLP(privilegedCarForm.getLicensePlate());
			if(!StringUtil.isNullOrBlank(licensePlate)){
				String[] param = {""};
				setErrorsToRequest(request, TmsConstants.U1029 ,param);
				return mapping.findForward(TOUPDATE);
			}
		}
		if(!privilegedCarForm.getTempLicensePlate().equals(oldTempLicensePlate)){
			String tempLicensePlate  = "";
			tempLicensePlate = car.findInputInfoTemLP(privilegedCarForm.getTempLicensePlate());
			if(!StringUtil.isNullOrBlank(tempLicensePlate)){
				String[] param = {""};
				setErrorsToRequest(request, TmsConstants.U8008 ,param);
				return mapping.findForward(TOUPDATE);
			}
		}
		
		CarPrivilegedCarDetailController controller = new CarPrivilegedCarDetailController();
		controller.executeUpdate(uc);

		logger.debug(this.getClass().getName() + "#execute was completed.");
		return mapping.findForward(TmsConstants.SUCCESS);
	}
	
	/** 
     * 判断是否为日期格式验证
     * @param str 需要验证的日期
     * @return true/false
     */  
	public boolean isValidDate(String str) {  
        DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");  
        try{  
            Date date = (Date)formatter.parse(str);  
            return str.equals(formatter.format(date));  
        }catch(Exception e){  
            return false;  
        }  
    }  
	
	/** 
     * 判断是否为数字 
     * @param str 需要验证的内容
     * @return true/false
     */  
    public static boolean isNumeric(String str) {  
        for (int i = str.length(); --i >= 0;) {  
            if (!Character.isDigit(str.charAt(i))) {  
                return false;  
            }  
        }  
        return true;  
    }  

}
